#!/bin/bash

su root -c "rpm -ivh devtoolset-8*.rpm"

src_dir=$PWD
build_root=~/tools

mkdir -p $build_root
cd $src_dir
tar xvf Python-2.7.15.tar.xz -C $build_root
tar xvf Python-3.6.6.tar.xz -C $build_root
tar zxvf vim-v8.2.0766.tar.gz -C $build_root
mv ~/.vim/bundle/YouCompleteMe ~/.vim/bundle/YouCompleteMe_bak
tar zxvf YouCompleteMe-ed423e8a.tar.gz -C ~/.vim/bundle

# build python2
cd $build_root/Python-2.7.15
python2_dir=/opt/python-2.7.15
./configure --prefix=$python2_dir --enable-shared
make -j8
su root -c "make install"
su root -c "cp $python2_dir/lib/libpython2.7.so.1.0 /usr/lib64"

# build python3，先编动态库，因为vim只能加载动态python库文件，再编译静态库给ycm_core.so使用
cd $build_root/Python-3.6.6
python3_dir=/opt/python-3.6.6
./configure --prefix=$python3_dir --enable-shared
make -j8

# 因为vim编译configure检测到python3动态库名为libpython3.6m.a,vim启动时会从系统目录查找libpython3.6m.a
su root -c "cp libpython3.6m.so.1.0 /usr/lib64/libpython3.6m.a"

CFLAGS="-fPIC" ./configure --prefix=$python3_dir --disable-shared
make -j8
su root -c "make install"

# build vim
cd $build_root/vim
git co .
./configure \
    --enable-pythoninterp=yes \
    --with-python-config-dir=$python2_dir/lib/python2.7 \
    --enable-python3interp=yes \
    --with-python3-config-dir=$python3_dir/lib/python3.6/config-3.6m-x86_64-linux-gnu \
    --with-python3-command=$python3_dir/bin/python3
make -j8
su root -c "make install"

# build ycm
source /opt/rh/devtoolset-8/enable 
cd $build_root
mkdir build_ycm; cd build_ycm
cp $src_dir/libclang.so.11 .
cmake -G "Unix Makefiles" -DEXTERNAL_LIBCLANG_PATH=./libclang.so.11 . ~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp/ -DPYTHON_EXECUTABLE=$python3_dir/bin/python3
make -j8
mv ./libclang.so.11 ~/.vim/bundle/YouCompleteMe/third_party/ycmd

cd ~/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/watchdog_deps/watchdog/
$python3_dir/bin/python3 setup.py build --build-base=build/3 --build-lib=build/lib3
